<template>
 

  <el-container>
    <el-aside width="350px">
      <el-tabs type="border-card">
        <el-tab-pane label="源数据">
          <div  class="text item" style=" display: flex; justify-content: end;">
            <el-button size="mini" type="text" @click="srcRun">运行</el-button>
            <el-button size="mini" type="text" @click="remove('gps-pointss')">移除</el-button>
          </div>
          <el-form :model="srcParameter" :rules="srcRules" ref="srcParameter">
            <el-form-item prop="srcTable" label="目标数据">
              <el-input  v-model="srcParameter.srcTable" autocomplete="off" placeholder="目标数据"></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="数据栅格化">
          <div  class="text item" style=" display: flex; justify-content: end;">
            <el-button size="mini" type="text" @click="gridParamsRun">运行</el-button>
            <el-button size="mini" type="text" @click="remove('density')">移除</el-button>
          </div>
          <el-form :model="gridParams" :rules="gridParamsRules" ref="gridParams">
            <el-form-item prop="srcTable" label="目标数据">
              <el-input  v-model="gridParams.srcTable" autocomplete="off" placeholder="目标数据"></el-input>
            </el-form-item>
            <el-form-item prop="gridType" label="栅格类型">
              <el-input  v-model="gridParams.gridType" autocomplete="off" placeholder="栅格类型" ></el-input>
            </el-form-item>       
            <el-form-item prop="radius" label="栅格范围">
              <el-input  v-model="gridParams.radius" autocomplete="off" placeholder="栅格范围" ></el-input>
            </el-form-item>                
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="点密度求值">
          <div  class="text item" style=" display: flex; justify-content: end;">
            <el-button size="mini" type="text" @click="densityRun">运行</el-button>
             <el-button size="mini" type="text" @click="remove('radius_num')">移除</el-button>
          </div>
          <el-form :model="densityParameter" :rules="rules" ref="densityParameter">
            <el-form-item prop="srcTable" label="目标数据">
              <el-input  v-model="densityParameter.srcTable" autocomplete="off" placeholder="目标数据"></el-input>
            </el-form-item>
            <el-form-item prop="gridType" label="栅格类型">
              <el-input  v-model="densityParameter.gridType" autocomplete="off" placeholder="栅格类型" ></el-input>
            </el-form-item>
            <el-form-item prop="radius" label="范围距离">
              <el-input  v-model="densityParameter.radius" autocomplete="off" placeholder="范围距离" ></el-input>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="核密度分析">
          <div  class="text item" style=" display: flex; justify-content: end;">
            <el-button size="mini" type="text" @click="pitDensity">运行</el-button>
            <el-button size="mini" type="text" @click="remove('center')">移除</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="线密度分析">
          <div  class="text item" style=" display: flex; justify-content: end;">
            <el-button size="mini" type="text" @click="lineDensity">运行</el-button>
            <el-button size="mini" type="text" @click="remove('center')">移除</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-aside>
    <el-main>
      <div class="mapbox-maps">
        <div id="map">      
        </div> 
      </div>   
    </el-main>
  </el-container>  
</template>
<script>
export default{
    name:'PostgisDensityAnalysis',
    data(){
      return{        
        drawer: false,
        map:{},
        geojson: {        
          type:'geojson',
          data:{
          "type": "FeatureCollection",
          "features":[]
          }
        },
        jsonData: {},
        srcParameter:{
          srcTable:"jzd",//原始数据
        },
        gridParams:{
          srcTable:"jzd",//原始数据
          gridType: 10,//栅格类型（矩形，六边形，圆）
          radius:0.00009,// 栅格范围
        },
        densityParameter:{
          srcTable:"jzd",//原始数据
          gridType: "quad_segs=1",// 栅格类型
          radius:0.0001,// 范围
        },
        srcRules: {
          srcTable: [
            { required: true, message: '请输入原始数据', trigger: 'blur' },
          ],                
        },
        gridParamsRules: {
          srcTable: [
            { required: true, message: '请输入原始数据', trigger: 'blur' },
          ],
          gridType: [
            { required: true, message: '请输入栅格类型', trigger: 'blur' },
          ],
          radius:[
            {required: true, message: '请输入栅格半径', trigger: 'blur' },
          ]                 
        },
        rules: {
          srcTable: [
            { required: true, message: '请输入原始数据', trigger: 'blur' },
          ],
          gridType: [
            { required: true, message: '请输入栅格类型', trigger: 'blur' },
          ],
          radius: [
            { required: true, message: '请输入范围距离', trigger: 'blur' },
          ],          
        },
      
      }
    },
    mounted() {
      this.loadMap()
    },
    beforeDestroy(){
      this.map.remove()

    },
    methods:{
        
      loadMap() {
          // 英文标注转换为中文   
          // mapboxgl.setRTLTextPlugin(
          //   "https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.1.0/mapbox-gl-rtl-text.js"
          // );
          this.map =  new mapboxgl.Map({
              accessToken: 'pk.eyJ1Ijoienh0d24iLCJhIjoiY2wzanV3bHduMTZwejNrcXcyd3B1bzBieiJ9.aW_TDqLomftwPvBu7OWqwQ',
              container: 'map',
              style: 'mapbox://styles/mapbox/outdoors-v10', // stylesheet location
              center: [116.79507,32.65542],  //[116.79507,32.65542], // starting position [lng, lat]
              zoom: 15, // starting zoom
              hash: false,
              //pitch: 45,  //地图的角度，不写默认是0，取值是0-60度，一般在3D中使用
              bearing: 0, //地图的初始方向，值是北的逆时针度数，默认是0，即是正北
              antialias: true, //抗锯齿，通过false关闭提升性能
          })
          // 设置语言
          // var language = new MapboxLanguage({ defaultLanguage: "zh" });
          // this.map.addControl(language);

          //地图导航
          var nav = new mapboxgl.NavigationControl();
          this.map.addControl(nav, 'top-right');

          // 比例尺
          var scale = new mapboxgl.ScaleControl({
              maxWidth: 100,
              unit: "metric"
          });
          this.map.addControl(scale,"bottom-left");

          // 全图
          this.map.addControl(new mapboxgl.FullscreenControl());
          // 定位
          this.map.addControl(
              new mapboxgl.GeolocateControl({
              positionOptions: {
                  enableHighAccuracy: true
              },
              trackUserLocation: true
              })
          );
          let that = this;
          this.map.on('load',function () {
            that.map.addSource('national-park',that.geojson);

            that.map.addLayer({
                'id': 'park-boundary',
                'type': 'fill',
                'source': 'national-park',
                'paint': {
                    'fill-color': '#e6141c',
                    'fill-opacity': 0.4
                },
            });
            that.map.addSource("gps-points",that.geojson);             			  
            that.map.addSource("gps-pointss",that.geojson);	  
            
            that.map.addSource("density",that.geojson);	//点密度分析 栅格像元
            that.map.addSource("center",that.geojson);	//点密度分析中心点	 

            that.map.addSource("radius_num",that.geojson);	//开始计算每个像素点再范围的的所有栅格像元的点个数

            that.map.addLayer({
              "id": "radius_num-text",
              "type": "symbol",
              "source": "radius_num",              
              "layout": {
                "visibility": "visible",			
                'text-field': '{ct}',		
                'text-size': 12
                },
              paint: {
                'text-color': '#FF0000'
                
              }				   
            })		
				
            that.map.addLayer({
              "id": "radius_num_line",
              "type": "line",
              "source": "radius_num",              
              "layout": {
                "visibility": "visible",			
              },
              "paint": {
                "line-opacity": 1,
                "line-color": "#000000",
                "line-width": 1,				
              }
            })   

            that.map.addLayer({
              id: "center",
              type: "circle",
              source: "center",
              paint: {
                "circle-radius": 0.03*1000,
                "circle-color": "#888800",
                "circle-blur":1,
                "circle-stroke-width":1, 
                "circle-stroke-color": "#000000",
                "circle-stroke-opacity": 1 
              }
            });

            //点密度分析效果展示 栅格像元          
            that.map.addLayer({
              "id": "density_line",
              "type": "line",
              "source": "density",              
              "layout": {
                  "visibility": "visible",			
              },
              "paint": {
                "line-opacity": 1,
                "line-color": "#00FF00",
                "line-width": 1,				
              }
            })   
                  
            that.map.addLayer({
              "id": "national-park",
              "type": "line",
              "source": "gps-points",              
              "layout": {
                "visibility": "visible",			
              },
              "paint": {
                  "line-opacity": 1,
                  "line-color": "#000000",
                  "line-width": 1,				
              },
                "maxzoom": 20,
                "minzoom": 0,
            })
            that.map.addLayer({
              "id": "national-park1",
              "type": "symbol",
              "source": "gps-points",              
              "layout": {
                "visibility": "visible",			
                'text-field': '{round}',		
                'text-size': 12
              },
              paint: {
                'text-halo-color': '#0000FF',
                //'text-halo-width': 2
              },
              "maxzoom": 20,
              "minzoom": 0,
            })

            //geojson  point 数据渲染
            that.map.addLayer({
                id: "gps-points",
                type: "circle",
                source: "gps-pointss",
                paint: {
                    "circle-radius":3,
                    "circle-color": "#ffffff",
                }
            });
              //geojson line 数据渲染
              that.map.addLayer({
                "id": "geojson-line",
                "type": "line",
                "source": "gps-pointss",              
                "layout": {
                "visibility": "visible",			
              },
              "paint": {
                "line-opacity": 1,
                "line-color": "#45D23E",
                "line-width": 1,				
              },
              "maxzoom": 20,
              "minzoom": 0,
              });
            
            //geojson polygon 数据渲染
            that.map.addLayer({
              "id": "geojson-polygon ",
              "type": "fill",
              "source": "gps-pointss",              
              "layout": {
                "visibility": "visible",			
              },
              "paint": {
                "fill-color":"#ffffff",
                'fill-opacity': 1,
                  }
              });
         //that.loadGeojson()
			
			//显示每个像元中心点
			//that.loadCenter();
      // that.pitDensity()					
              
    })
          
      },
      /**
       * 拷贝geojson
       */
      onCopy(e){
          console.log(e)
          alert(e)
      },	
      flyTo(lng,lat){
        this.map.flyTo({ center: [lng, lat], zoom: 10 })
      },
      lineDensity(){
        debugger
        let that = this  
        // that.flyTo( 109.7 , 18.65)          
        let fd =  new URLSearchParams()
        fd.append("bounds","")
        fd.append("srcTable","jzx" )
        fd.append("radius",100 )   
        fd.append("gridRadius","0.0009")           
        let url = "/linedensity/"
        that.$axios.post(url, fd)     
        .then((res)=> {          
          console.log(res)
          let features = []
          // let json = JSON.parse(res.data.data)
          res.data.data.forEach(e=>{
            let geom = JSON.parse(e.geom)    
            // features=geom.features	        
            
             features.push({
             "type": "Feature",
             "geometry":geom,
             "properties": {"value": e.param}
            })
          })

          
          that.map.getSource('center').setData({
              "type": "FeatureCollection",
              "features":[]
          })
          that.map.getSource('center').setData({
              "type": "FeatureCollection",
              "features":features
          })
        })
        .catch(function (error) {       
          console.log(error);
        })             

      },
      pitDensity(){
        debugger
        let that = this  
        that.flyTo( 109.7 , 18.65)          
        let fd =  new URLSearchParams()
        fd.append("srcTable","hainan")
        fd.append("radius",1000 )
        fd.append("scope",3000 )            
        let url = "/pitdensity/geojson"
        that.$axios.post(url, fd)     
        .then((res)=> {          
          console.log(res)
          // let features = []
          let json = JSON.parse(res.data.data)
          // res.data.data.forEach(e=>{
          //   let geom = JSON.parse(e.row_to_json.value)    
          //   features=geom.features	            
          // })

          
          that.map.getSource('center').setData({
              "type": "FeatureCollection",
              "features":[]
          })
          that.map.getSource('center').setData({
              "type": "FeatureCollection",
              "features":json.features
          })
        })
        .catch(function (error) {       
          console.log(error);
        })             
      }, 
      loadCenter(){
        debugger
          let that = this
          let url = "/analysis/point/center"
        that.$axios({
        url: url,
        method: 'post',
        data:{},
        })
        .then(function (res) {          
          console.log(res)
          let features = []
          res.data.data.forEach(e=>{
            let geom = JSON.parse(e.row_to_json.value)    
            features=geom.features			
            //features.push({
            // "type": "Feature",
            //  "geometry":geom,
            //  "properties": {"status": "status"}
            //})
          })
          that.map.getSource('center').setData({
          "type": "FeatureCollection",
          "features":[]
        })
        that.map.getSource('center').setData({
        "type": "FeatureCollection",
        "features":features
        })
        })
        .catch(function (error) {
        // handle error
        console.log(error);
        })   

      },	 
      densityRun(){
        let that = this
        that.$refs["densityParameter"].validate((valid) => {       
          if (valid) {                      
            let fd =  new URLSearchParams()
            fd.append("srcTable",that.densityParameter.srcTable)
            fd.append("gridType", that.densityParameter.gridType)
            fd.append("radius", that.densityParameter.radius)            
            let url = "/analysis/point/radius_num"
            that.$axios.post(url, fd)     
            .then((res)=> {          
              console.log(res)
              let features = []
              res.data.data.forEach(e=>{
                let geom = JSON.parse(e.row_to_json.value)    
                features=geom.features	            
              })
              that.map.getSource('radius_num').setData({
                  "type": "FeatureCollection",
                  "features":[]
              })
              that.map.getSource('radius_num').setData({
                  "type": "FeatureCollection",
                  "features":features
              })
            })
            .catch(function (error) {       
              console.log(error);
            })             
          } else {
            console.log('error submit!!');
            return false;
          }
        });                
      },  
      /**
        * 
        * 生成栅格数据
        */  
      gridParamsRun(){
        let that = this
        that.$refs["gridParams"].validate((valid) => {      
          if (valid) {                     
            let fd =  new URLSearchParams()
            fd.append("srcTable",that.gridParams.srcTable)
            fd.append("gridType", that.gridParams.gridType)
            fd.append("radius", that.gridParams.radius)            
            let url = "/analysis/point/density"
            that.$axios.post(url, fd)       
            .then(function (res) {          
              console.log(res)
              let features = []
              res.data.data.forEach(e=>{
                let geom = JSON.parse(e.row_to_json.value)    
                features=geom.features	            
              })
              that.map.getSource('density').setData({
                  "type": "FeatureCollection",
                  "features":[]
              })
              that.map.getSource('density').setData({
                  "type": "FeatureCollection",
                  "features":features
              })
            })
            .catch(function (error) {       
              console.log(error);
            })             
          } else {
            console.log('error submit!!');
            return false;
          }
        });                
      },
      /**
        * 渲染geojson数据
        * 
        */
      srcRun(){
        let that = this
        that.$refs["srcParameter"].validate((valid) => {       
          if (valid) {
            let that = this           
            let fd =  new URLSearchParams()
            fd.append("srcTable",that.srcParameter.srcTable)                     
            let url = "/analysis/geojson"
            that.$axios.post(url, fd)       
            .then(function (res) {          
              console.log(res)
              let features = []
              res.data.data.forEach(e=>{
                let geom = JSON.parse(e.geom)    
                features.push({
                "type": "Feature",
                "geometry":geom,
                "properties": {"status": "status"}
                })	
              
              })
              that.map.getSource('gps-pointss').setData({
                  "type": "FeatureCollection",
                  "features":[]
              })
              that.map.getSource('gps-pointss').setData({
                  "type": "FeatureCollection",
                  "features":features
              })
            })
            .catch(function (error) {       
              console.log(error);
            })             
          } else {
            console.log('error submit!!');
            return false;
          }
        });                
      },
      remove(sourceId){
        let that = this
        that.map.getSource(sourceId).setData({
            "type": "FeatureCollection",
            "features":[]
        })

      },
  }
}

</script>
<style scoped lang="scss">
 @import "../../../public/mapbox/mapbox-gl.css";
 .mapbox-maps {
    width: 100%;
    height: calc(100vh - 50px);
    position: relative;
    #map {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        bottom:0;
        right: 0;        
    }
    
}
.mapboxgl-canvas {
    outline: none;
}
  /* 隐藏mapbox商标 */
.mapboxgl-ctrl-logo {
    display: none;
} 
.el-aside {
    overflow: auto;
    box-sizing: border-box;
    flex-shrink: 0;
    width: 200px;
    // border: 1px solid red;
    line-height: 19px;
    padding: 10px;
    text-align: left;
}
.jv-container .jv-code.boxed {
    max-height: 100%;
}
</style>